<?php

/**
 * GalleryController Class
 *
 * @package Bd Gallery
 * @author Bebliuc George Cristian
 * @author Gianfranco Liporace
 * @copyright 2008-2010
 * @version 1.3
 * @access public
 * @permisions Modify, Redistribute but leave the credits alive :P
 * @use Noncommercial, for commercial use, please contact me at bebliuc.george@gmail.com, it's for free, but I need to know
 *
 */

class GalleryController extends PluginController {
    var $delete;


    public function __construct() {

        if (defined('CMS_BACKEND')) {
            AuthUser::load();
	        if ( ! AuthUser::isLoggedIn()) {
	            redirect(get_url('login'));
	        }
            $this->setLayout('backend');
            $this->assignToLayout('sidebar', new View('../../plugins/gallery/views/admin/sidebar'));
        } else {
            $page = Page::findByUri(Plugin::getSetting('gallery_page', 'gallery'));
            // get properties from the 'phisycal' page and assign them to the 'dispatched' one
            $this->parent = $page->parent;
            $this->title = $page->title;
            $this->breadcrumb = $page->breadcrumb;
            $this->slug = $page->slug;
            $layout_id = $this->getLayoutId($page);
            $layout = Layout::findById($layout_id);
            $this->setLayout($layout->name);
        }
    }

    /**
     *  Functions borrowed from a Dispatcher tutorial by Andrew Waters suggested
     * by Mike Barlow (snsmurfs) on the Wolfcms forum
     * http://www.band-x.org/blog/2009/10/14/dispatcher-actions-in-wolf-6-0
     */

    /**
	 * Return the content from the view for presentation in the front
	 *
	 * @param mixed $part    (optional)
	 * @param mixed $inherit (optional)
	 * @return mixed
	 */
	public function content($part=false, $inherit=false) {
		if (!$part)
			return $this->content;
		else
			return false;
	}
    /**
	 * Get the pages's layout id
	 *
	 * @param mixed $page
	 * @return mixed
	 */
	private function getLayoutId($page) {
		if ($page->layout_id)
			return $page->layout_id;
		else if ($page->parent)
				return $this->getLayoutId($page->parent);
			else
				exit ('This page is not valid...');
	}


    /** frontend functions  **/
    public function view($cid = null, $pid = null) {
        $this->display('../../plugins/gallery/views/frontend/view', array('cid' => $cid,
                                                                          'pid' => $pid));
    }

    public function view_photo($id) {
        $settings = Plugin::getAllSettings('gallery');
        $photo = Photos::findById($id);
        $filename = $photo->getFileName();
        $images_folder = $settings['images_folder'];
        $image_path = CMS_ROOT . "/public/" . $settings['images_folder'] . "/" . $filename;
        if ($details = getimagesize($image_path)) {
            $photo->addVisitor();
            $photo->save();
            header('Content-Type: ' . ($details['mime']));
            echo file_get_contents($image_path);
        }
    }

    public function tags($tags) {
        $this->display('../../plugins/gallery/views/frontend/view', array('tags' => $tags));
    }


    /** backend functions **/

    public function index() {

        $this->display('gallery/views/admin/index');
    }

    public function add_image() {
        $this->display('gallery/views/admin/add_image');
    }
    public function upload_image() {

        $settings = Plugin::getAllSettings('gallery');
        //begining: display a list of downloads
        //sanitize file upload dir

        $images_folder = $settings['images_folder'];
        if(strpos($images_folder, '/') === 0 || strpos($images_folder, '\\') === 0) {
            //Leading slash.  Kill it and default to images/gallery
            $images_folder = 'images/gallery/';
        }

        if(strpos($images_folder, '..') !== false) {
            //downward directories.  Kill it and default to images/gallery
            $images_folder = 'images/gallery/';
        }

        $images_dir = CMS_ROOT . '/public/' . $images_folder;

        // initialization

        $result_final = "";

        $counter = 0;

        // List of our known photo types
        $known_photo_types = array('image/pjpeg' => 'jpg', 'image/jpeg' => 'jpg',
                'image/gif' => 'gif', 'image/bmp' => 'bmp', 'image/x-png' => 'png', 'image/png' => 'png');

        // GD Function List
        $gd_function_suffix = array('image/pjpeg' => 'JPEG', 'image/jpeg' => 'JPEG',
                'image/gif' => 'GIF', 'image/bmp' => 'WBMP', 'image/x-png' => 'PNG', 'image/png' => 'PNG');

        // get list of uploaded photos
        $photos = $_FILES['photo_filename'];

        // Fetch the photo caption array
        $photo_caption = $_POST['photo_caption'];
        $photo_title = $_POST['photo_title'];


        while ($counter < count($photos['name'])) {
            if ($photos['size'][$counter] > 0) {
                if (!array_key_exists($photos['type'][$counter], $known_photo_types)) {
                    Flash::set('error', __('BD Gallery - You\'re trying to trick me. Please upload a PHOTO.'));
                    redirect_to(get_url('plugin/gallery/add_image'));
                }
                else {
                    $photo = new Photos();
                    $data = array('photo_title' => $photo_title[$counter],
                                  'photo_filename' => 0,
                                  'photo_caption' => $photo_caption[$counter],
                                  'photo_category' => $_POST['category']);
                    $photo->setFromData($data);
                    $photo->save();

                    $PDO = Record::getConnection();
                    $new_id = $PDO->lastInsertId();
                    $filetype = $photos['type'][$counter];
                    $extention = $known_photo_types[$filetype];
                    $filename = $new_id . "." . $extention;

                    $photo = Photos::findbyId($new_id);
                    $photo->setFilename($filename);
                    $photo->save();
                    // Move the uploaded file into the gallery folder
                    if (!move_uploaded_file($photos['tmp_name'][$counter], $images_dir . $filename)) {
                        Flash::set('error', 'BD Gallery - '. __('Error in moving the uploaded file. Error: ' . $photos_uploaded['error'][0]));
                        redirect_to(get_url('plugin/gallery/add_image'));
                    }

                    // Let's get the Thumbnail size
                    $size = GetImageSize($images_dir . $filename);

                    if($settings['ratio'] == "1") {
                        if($size[0] > $size[1]) {
                            $thumbnail_width = $settings['thumbnail_width'];
                            $thumbnail_height = (int)($settings['thumbnail_height'] * $size[1] / $size[0]);
                        }
                        else {
                            $thumbnail_width = (int)($settings['thumbnail_width'] * $size[0] / $size[1]);
                            $thumbnail_height = $settings['thumbnail_height'];
                        }
                    }
                    else {

                        $thumbnail_width = $settings['thumbnail_width'];
                        $thumbnail_height = $settings['thumbnail_height'];

                    }


                    // Build Thumbnail with GD 1.x.x, you can use the other described methods too
                    $function_suffix = $gd_function_suffix[$filetype];
                    $function_to_read = "ImageCreateFrom" . $function_suffix;
                    $function_to_write = "Image" . $function_suffix;

                    // Read the source file
                    $source_handle = $function_to_read($images_dir . $filename);

                    if ($source_handle) {

                        if($settings['quality'] == '1') {
                            // Let's create an blank image for the thumbnail
                            $destination_handle = imagecreatetruecolor($thumbnail_width, $thumbnail_height);
                            // Now we resize it
                            imagecopyresampled($destination_handle, $source_handle, 0, 0, 0, 0, $thumbnail_width,
                                    $thumbnail_height, $size[0], $size[1]);
                        }
                        else {
                            // Let's create an blank image for the thumbnail
                            $destination_handle = ImageCreate($thumbnail_width, $thumbnail_height);
                            // Now we resize it
                            ImageCopyResized($destination_handle, $source_handle, 0, 0, 0, 0, $thumbnail_width,
                                    $thumbnail_height, $size[0], $size[1]);
                        }
                    }

                    // Let's save the thumbnail
                    $function_to_write($destination_handle, $images_dir . "tb_" . $filename);
                    ImageDestroy($destination_handle);
                    //


                }
            }
            $counter++;
        }
        Flash::set('success', __('BD Gallery - The images have been added successfully.'));
        redirect_to(get_url('plugin/gallery/add_image'));

    }


    public function delete($id) {
        if (Category::deleteWhere('Category', 'id=:id', array(':id' => $id))) {
            Flash::set('success', 'BD Gallery - ' . __('The album has been deleted successfully.'));
        } else {
            Flash::set('error', 'BD Gallery - ' . __('An error has occurred. Album not deleted.'));
        }
        redirect(get_url('plugin/gallery/index'));
    }

    public function add_album() {

        $this->display('gallery/views/admin/add_album');
    }

    public function create_album() {
        $data = array('category_name' => htmlentities($_POST['albumname']),
                      'category_description' => htmlentities($_POST['albumdescription']));
        if ($data['category_name'] == "" or $data['category_description'] == "") {
            Flash::set('error', 'BD Gallery - ' . __('An error has occurred. You need to supply a title and a description.'));
            redirect(get_url('plugin/gallery/add_album'));
        } else {
            $category = new Category();
            $category->setFromData($data);
            if ($category->save()) {
                Flash::set('success', 'BD Gallery - ' . __('The album has been created successfully.'));
            } else {
                $conn = Record::getConnection();
                $error = $conn->errorInfo();
                Flash::set('error', 'BD Gallery - ' . __('An error has occurred. Album not created. Error message: ' . $error[2]));
            }
            redirect(get_url('plugin/gallery/index'));
        }
    }

    public function edit_album($id) {
        $this->display('gallery/views/admin/edit_album', array('id' => $id));
    }

    public function _edit_album() {
        $data = array('id' => $_POST['id'],
                      'category_name' => htmlentities($_POST['name']),
                      'category_description' => htmlentities($_POST['description']),
                      'tags' => htmlentities($_POST['tags']));
        if ($data['category_name'] == "" or $data['category_description'] == "" or $data['id'] == "") {
            Flash::set('error', 'BD Gallery - ' . __('An error has occurred. You need to supply a title and a description.'));
            redirect(get_url('plugin/gallery/edit_album/' . $id));
        }
        else {
            $category = new Category();
            // $category->findOneFrom('Category', 'id=:id', array(':id' => $data['id']));
            $category->setFromData($data);
            if ($category->save()) {
                Flash::set('success', 'BD Gallery - ' . __('Album details saved.'));
                redirect(get_url('plugin/gallery/'));
            }
            else {
                Flash::set('error', 'BD Gallery - ' . __('An error has occurred. Album details not saved.'));
                redirect(get_url('plugin/gallery/edit_album/' . $id));
            }

        }
    }

    public function view_album($id) {

        $this->display('gallery/views/admin/view_album', array('id' => $id));
    }

    public function delete_photo($id) {
        $category = Photos::findCategoryByPhotoId($id);
        $delete_file = Plugin::getSetting('delete_file', 'gallery');
        $images_folder = Plugin::getSetting('images_folder', 'gallery');
        $images_path = CMS_ROOT . '/public/' . $images_folder;
        $photo_filename = Photos::findById($id)->getFilename();
        if (Photos::deleteWhere('Photos', 'id=:id', array(':id' => $id))) {
            if ($delete_file == '1') {
                // unlink photo and thumbnail
                unlink($images_path . $photo_filename);
                unlink($images_path . 'tb_' . $photo_filename);
            }
            Flash::set('success', 'BD Gallery - ' . __('The album has been deleted successfully.'));
        } else {
            Flash::set('error', 'BD Gallery - ' . __('An error has occurred. Photo not deleted.'));
        }
        redirect(get_url('plugin/gallery/view_album/' . $category));
    }

    public function edit_photo($id) {
        $this->display('gallery/views/admin/edit_photo', array('id' => $id));
    }

    public function _edit_photo() {

        // TODO: need to use same name for vars in both views and models
        $data = array('id' => $_POST['photoid'],
                      'photo_title' => htmlentities($_POST['phototitle']),
                      'photo_caption' => htmlentities($_POST['photodescription']),
                      'photo_category' => $_POST['category']);

        if ($data['photo_title'] == "" or $data['id'] == "") {
            Flash::set('error', 'BD Gallery - ' . __('Please fill the "Title" field.'));
            redirect(get_url('plugin/gallery/edit_photo/' . $id));
        }
        else {
            $photo = new Photos();
            // $photo->findById($data['id']);
            $photo->setFromData($data);

            if ($photo->save()) {
                Flash::set('success', 'BD Gallery - ' . __('The settings have been update :)'));
                redirect(get_url('plugin/gallery/view_album/' . $data['photo_category']));
            }
            else {
                Flash::set('error', 'BD Gallery - ' . __('An error has occured. Photo not edited.'));
                redirect(get_url('plugin/gallery/edit_photo/' . $data['id']));
            }

        }
    }


    public function settings() {
        $this->display('gallery/views/admin/settings', Plugin::getAllSettings('gallery'));
    }

    function save_settings() {
        // Quick hack, I'll check for all settings later
        if (!array_key_exists('images_folder', $_POST) ||
            !array_key_exists('gallery_page', $_POST) ||
            !array_key_exists('delete_file', $_POST) ||
            !array_key_exists('title', $_POST) ||
            !array_key_exists('script', $_POST) ||
            !array_key_exists('thumbnail_width', $_POST) ||
            !array_key_exists('thumbnail_height', $_POST) ||
            !array_key_exists('framework', $_POST) ||
            !array_key_exists('thumbs_per_row', $_POST) ||
            !array_key_exists('ratio', $_POST) ||
            !array_key_exists('quality', $_POST)) {
            Flash::set('error', 'BD gallery - '.__('Form was not posted. Missing fields required.'));
        } else {
            $settings = $_POST;
            $ret = Plugin::setAllSettings($settings, 'gallery');
            if ($ret) {
                Flash::set('success', 'BD gallery - '.__('The settings have been saved.'));
            }
            else {
                Flash::set('error', 'BD gallery - ' . __('An error occured trying to save the settings.'));
            }
        }
        redirect(get_url('plugin/gallery/settings'));
    }

    public function documentation() {
        $this->display('gallery/views/admin/documentation');
    }
}
